/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.envconfig.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import javax.servlet.ServletException;
import org.hibernate.envers.Audited;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
 *
 * @author Pete
 */
@Entity
@Audited
public class Environment {
    @Transient
    private final Logger logger = Logger.getLogger(Environment.class.getName());
    
    @Transient
    private EntityManager em;

    @Id
    @GeneratedValue
    private int id;

    @Column(unique=true)
    private String name;

    private String description;

    @OneToMany(mappedBy = "environment", cascade=CascadeType.ALL)
    private List<Group> groups = new ArrayList<Group>();

    public Environment(EntityManager em, String name, String description) {
        this.em = em;
        this.name = name;
        this.description = description;
    }

    public List<Group> getGroups() {
        return em.createQuery("SELECT g FROM Group g", Group.class).getResultList();
    }

    public Group getGroup(String groupName) {
        logger.info("Getting the group: " + groupName);

        return em.createQuery(
                "SELECT g FROM Group g WHERE g.name = :name", Group.class)
                .setParameter("name", groupName).getSingleResult();
    }

    public void doCreateGroup(StaplerRequest req, StaplerResponse res) throws ServletException, IOException {
        String name = req.getParameter("name");
        String description = req.getParameter("description");

        // make sure there is no existing group
        List groups = em.createQuery(
                "SELECT g FROM Group g WHERE g.name = :name and g.environment = :environment")
                .setParameter("name", name)
                .setParameter("environment", this)
                .getResultList();

        if (groups.size() > 0) {
            // sorry, can't create group with same name
        } else {
            Group group = new Group(em, this, name, description);
            groups.add(group);
            em.persist(this);
            em.flush();
            res.sendRedirect2("group/" + group.getId());
        }
    }
}
